#!/usr/bin/env python3
"""
持久化系统测试
测试数据库模型、工作区管理、分析会话管理等功能
"""
import sys
import os
import unittest
import tempfile
import shutil
from datetime import datetime

# 添加backend目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'backend'))

from database import DatabaseManager
from models import Base, Workspace, AnalysisSession, Conversation, UserConfig
from workspace_service import WorkspaceService, AnalysisSessionService, ConversationService

class TestPersistenceSystem(unittest.TestCase):
    """持久化系统测试类"""
    
    def setUp(self):
        """测试前准备"""
        # 创建临时数据库
        self.test_db_fd, self.test_db_path = tempfile.mkstemp()
        self.db_url = f'sqlite:///{self.test_db_path}'
        
        # 初始化数据库管理器
        self.db_manager = DatabaseManager(self.db_url)
        
        # 初始化服务
        self.workspace_service = WorkspaceService()
        self.session_service = AnalysisSessionService()
        self.conversation_service = ConversationService()
        
        # 替换全局数据库管理器
        import workspace_service
        workspace_service.db_manager = self.db_manager
        
    def tearDown(self):
        """测试后清理"""
        os.close(self.test_db_fd)
        os.unlink(self.test_db_path)
    
    def test_database_creation(self):
        """测试数据库表创建"""
        # 检查所有表是否存在
        with self.db_manager.get_session() as session:
            # 尝试查询每个表
            session.query(Workspace).count()
            session.query(AnalysisSession).count()
            session.query(Conversation).count()
            session.query(UserConfig).count()
        
        print("[PASS] 数据库表创建测试通过")
    
    def test_workspace_crud(self):
        """测试工作区CRUD操作"""
        # 创建工作区
        workspace_data = self.workspace_service.create_workspace(
            name="测试工作区",
            description="这是一个测试工作区",
            settings={"test": True}
        )
        
        self.assertIsNotNone(workspace_data['id'])
        self.assertEqual(workspace_data['name'], "测试工作区")
        self.assertEqual(workspace_data['description'], "这是一个测试工作区")
        self.assertEqual(workspace_data['settings']['test'], True)
        
        workspace_id = workspace_data['id']
        
        # 读取工作区
        workspace = self.workspace_service.get_workspace(workspace_id)
        self.assertIsNotNone(workspace)
        self.assertEqual(workspace['name'], "测试工作区")
        
        # 更新工作区
        updated_workspace = self.workspace_service.update_workspace(
            workspace_id,
            name="更新的工作区",
            description="更新的描述"
        )
        self.assertEqual(updated_workspace['name'], "更新的工作区")
        self.assertEqual(updated_workspace['description'], "更新的描述")
        
        # 获取工作区列表
        workspaces = self.workspace_service.get_workspaces()
        self.assertEqual(len(workspaces), 1)
        
        # 删除工作区
        success = self.workspace_service.delete_workspace(workspace_id)
        self.assertTrue(success)
        
        # 验证软删除
        workspace = self.workspace_service.get_workspace(workspace_id)
        self.assertIsNone(workspace)
        
        print("[PASS] 工作区CRUD测试通过")
    
    def test_analysis_session_crud(self):
        """测试分析会话CRUD操作"""
        # 先创建工作区
        workspace = self.workspace_service.create_workspace("测试工作区")
        workspace_id = workspace['id']
        
        # 创建分析会话
        session_data = self.session_service.create_session(
            workspace_id=workspace_id,
            name="测试会话",
            description="测试分析会话"
        )
        
        self.assertIsNotNone(session_data['id'])
        self.assertEqual(session_data['workspace_id'], workspace_id)
        self.assertEqual(session_data['name'], "测试会话")
        self.assertEqual(session_data['status'], "created")
        
        session_id = session_data['id']
        
        # 读取分析会话
        session = self.session_service.get_session(session_id)
        self.assertIsNotNone(session)
        self.assertEqual(session['name'], "测试会话")
        
        # 更新分析会话
        updated_session = self.session_service.update_session(
            session_id,
            name="更新的会话",
            status="completed",
            tags=["test", "important"],
            notes="测试备注"
        )
        self.assertEqual(updated_session['name'], "更新的会话")
        self.assertEqual(updated_session['status'], "completed")
        self.assertEqual(updated_session['tags'], ["test", "important"])
        self.assertEqual(updated_session['notes'], "测试备注")
        
        # 获取工作区的会话列表
        sessions = self.session_service.get_sessions(workspace_id=workspace_id)
        self.assertEqual(len(sessions), 1)
        self.assertEqual(sessions[0]['id'], session_id)
        
        # 删除分析会话
        success = self.session_service.delete_session(session_id)
        self.assertTrue(success)
        
        # 验证删除
        session = self.session_service.get_session(session_id)
        self.assertIsNone(session)
        
        print("[PASS] 分析会话CRUD测试通过")
    
    def test_conversation_management(self):
        """测试对话历史管理"""
        # 创建工作区和会话
        workspace = self.workspace_service.create_workspace("测试工作区")
        session = self.session_service.create_session(
            workspace_id=workspace['id'],
            name="测试会话"
        )
        session_id = session['id']
        
        # 添加用户消息
        user_message = self.conversation_service.add_message(
            session_id=session_id,
            message_type="user",
            content="这是一个测试问题",
            context={"test": True}
        )
        
        self.assertEqual(user_message['message_type'], "user")
        self.assertEqual(user_message['content'], "这是一个测试问题")
        self.assertEqual(user_message['context']['test'], True)
        
        # 添加AI回复
        ai_message = self.conversation_service.add_message(
            session_id=session_id,
            message_type="ai",
            content="这是AI的回复"
        )
        
        self.assertEqual(ai_message['message_type'], "ai")
        self.assertEqual(ai_message['content'], "这是AI的回复")
        
        # 获取对话历史
        history = self.conversation_service.get_conversation_history(session_id)
        self.assertEqual(len(history), 2)
        
        # 验证消息顺序（按时间排序）
        self.assertEqual(history[0]['message_type'], "user")
        self.assertEqual(history[1]['message_type'], "ai")
        
        # 清空对话历史
        success = self.conversation_service.clear_conversation_history(session_id)
        self.assertTrue(success)
        
        # 验证清空
        history = self.conversation_service.get_conversation_history(session_id)
        self.assertEqual(len(history), 0)
        
        print("[PASS] 对话历史管理测试通过")
    
    def test_data_relationships(self):
        """测试数据关系"""
        # 创建工作区
        workspace = self.workspace_service.create_workspace("测试工作区")
        workspace_id = workspace['id']
        
        # 创建多个分析会话
        session1 = self.session_service.create_session(workspace_id, "会话1")
        session2 = self.session_service.create_session(workspace_id, "会话2")
        
        # 为每个会话添加对话
        self.conversation_service.add_message(session1['id'], "user", "问题1")
        self.conversation_service.add_message(session1['id'], "ai", "回答1")
        self.conversation_service.add_message(session2['id'], "user", "问题2")
        
        # 验证关系
        sessions = self.session_service.get_sessions(workspace_id=workspace_id)
        self.assertEqual(len(sessions), 2)
        
        history1 = self.conversation_service.get_conversation_history(session1['id'])
        history2 = self.conversation_service.get_conversation_history(session2['id'])
        
        self.assertEqual(len(history1), 2)
        self.assertEqual(len(history2), 1)
        
        # 删除工作区应该级联删除会话和对话（软删除）
        self.workspace_service.delete_workspace(workspace_id)
        
        # 验证软删除 - 工作区被标记为不活跃，但会话仍存在
        # 因为我们的删除是软删除，会话不会被自动删除
        # 这里应该验证工作区不再可见，而不是会话被删除
        workspace = self.workspace_service.get_workspace(workspace_id)
        self.assertIsNone(workspace)  # 软删除后工作区应该不可见
        
        print("[PASS] 数据关系测试通过")
    
    def test_data_persistence(self):
        """测试数据持久化"""
        # 创建数据
        workspace = self.workspace_service.create_workspace("持久化测试")
        session = self.session_service.create_session(
            workspace['id'], 
            "持久化会话",
            description="测试持久化功能"
        )
        
        # 添加分析结果
        analysis_results = {
            "total_logs": 1000,
            "error_count": 50,
            "components": {"app": 800, "framework": 200}
        }
        
        ai_analysis = {
            "initial_analysis": "发现多个错误需要关注",
            "suggested_questions": ["错误的根本原因是什么？", "如何修复这些问题？"]
        }
        
        updated_session = self.session_service.update_session(
            session['id'],
            analysis_results=analysis_results,
            ai_analysis=ai_analysis,
            status="completed"
        )
        
        # 验证数据保存
        self.assertEqual(updated_session['analysis_results'], analysis_results)
        self.assertEqual(updated_session['ai_analysis'], ai_analysis)
        self.assertEqual(updated_session['status'], "completed")
        
        # 重新读取验证持久化
        persisted_session = self.session_service.get_session(session['id'])
        self.assertEqual(persisted_session['analysis_results'], analysis_results)
        self.assertEqual(persisted_session['ai_analysis'], ai_analysis)
        
        print("[PASS] 数据持久化测试通过")
    
    def test_uuid_handling(self):
        """测试UUID处理"""
        # 创建工作区
        workspace = self.workspace_service.create_workspace("UUID测试")
        workspace_id = workspace['id']
        
        # 验证UUID格式
        import re
        uuid_pattern = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
        self.assertTrue(uuid_pattern.match(workspace_id))
        
        # 创建会话
        session = self.session_service.create_session(workspace_id, "UUID测试会话")
        session_id = session['id']
        
        # 验证会话UUID
        self.assertTrue(uuid_pattern.match(session_id))
        
        # 创建对话
        message = self.conversation_service.add_message(session_id, "user", "测试消息")
        message_id = message['id']
        
        # 验证消息UUID
        self.assertTrue(uuid_pattern.match(message_id))
        
        # 验证外键关系
        self.assertEqual(message['session_id'], session_id)
        self.assertEqual(session['workspace_id'], workspace_id)
        
        print("[PASS] UUID处理测试通过")

def run_persistence_tests():
    """运行持久化系统测试"""
    print("[TEST] 开始持久化系统测试...")
    print("=" * 50)
    
    # 创建测试套件
    test_suite = unittest.TestSuite()
    
    # 添加测试用例
    test_cases = [
        'test_database_creation',
        'test_workspace_crud',
        'test_analysis_session_crud',
        'test_conversation_management',
        'test_data_relationships',
        'test_data_persistence',
        'test_uuid_handling'
    ]
    
    for test_case in test_cases:
        test_suite.addTest(TestPersistenceSystem(test_case))
    
    # 运行测试
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(test_suite)
    
    print("=" * 50)
    if result.wasSuccessful():
        print("[SUCCESS] 所有持久化系统测试通过！")
        return True
    else:
        print("[FAIL] 部分测试失败")
        print(f"失败: {len(result.failures)}, 错误: {len(result.errors)}")
        return False

if __name__ == '__main__':
    success = run_persistence_tests()
    exit(0 if success else 1)
